package com.freewill.menu;
import com.freewill.main.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.freewill.anim.LeftMenuCloseAnimation;
import com.freewill.anim.LeftMenuOpenAnimation;
import com.freewill.common.MainActivity;
import com.freewill.my.MySettingActivity;
import com.freewill.utils.UrlCons;
import com.freewill.utils.UtilCons;

public class LeftMenu implements OnClickListener, OnTouchListener{

    /**
     * 왼쪽 메뉴를 불르는 Activity 명
     */
    Activity act = null;
    
    /**
     * 왼쪽 메뉴를 부르는 Activity를 구분하기 위한 변수
     */
    int sort = 0;
    
    /**
     * 공유버튼(날개)가 보였다 안보였다 하기 위해서
     */
    ImageView iv;
    
    /**
     * 메인 Layout
     */
    LinearLayout mLlMain;
    
    /**
     * 왼쪽 메뉴 Layout
     */
    LinearLayout mLlMenu;
    
    FrameLayout.LayoutParams leftMenuLayoutPrams;
    FrameLayout.LayoutParams slidingPanelParameters;
    
    /**
     * 전체 화면의 넒이 값을 구하기 위한 값
     */
    DisplayMetrics metrics;
    
    /**
     * 왼쪽 메뉴 넒이 값
     */
    int viewWidth;
    
    /**
     * 현재 왼쪽 메뉴가 보여지고 있는지의 상태
     * true :: 왼쪽 메뉴 보여지고 있는 상태
     * false :: 왼쪽 메뉴 보이지 않고 있는 상태
     */
    boolean isLeftExpanded;
    
    /**
     * Scroll View
     */
    ScrollView mScrollMySetting;
    
    /**
     * 왼쪽메뉴 클릭시 dim 처리를 위한 View
     */
    ImageView mIvDimView;
	
    /**
     * 'My프리윌' Layout
     */
    RelativeLayout mRlMy;
    
	/**
	 * '홈으로' Layout  
	 */
    RelativeLayout mRlHome;
    
	/**
     * '커뮤니티' Layout  
     */
    RelativeLayout mRlCommunity;
	
	/**
     * '공유하기' Layout  
     */
    RelativeLayout mRlShare;

	/**
     * '요청하기' Layout  
     */
    RelativeLayout mRlRequest;
    
	/**
     * '이벤트' Layout  
     */
    RelativeLayout mRlEvent;
    
    /**
     * '광고' Layout
     */
    LinearLayout mLlMenuAd;
    
    /**
     * x 버튼
     */
    ImageButton mBtnExit;
	
	/**
     * 왼쪽 드래그시 좌측메뉴 사라지게 하기 위한 변수 
     * 처음 터치한 X좌표값
     */
    float pressedX = 0;
    
    public LeftMenu(Activity act, int sort, ImageView iv){
        this.act = act;
        this.sort = sort;
        this.iv = iv;
    }
    
    @SuppressWarnings("deprecation")
    public void initLeftMenu() {
        Log.i("sykim","LeftMenu_initLeftMenu START");
        metrics = new DisplayMetrics();
        
        act.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        
        viewWidth = (int) ((metrics.widthPixels) * 0.6675);
        
        mLlMain = (LinearLayout)act.findViewById(R.id.ll_mainlayout);
        
        slidingPanelParameters = (FrameLayout.LayoutParams) mLlMain.getLayoutParams();
        slidingPanelParameters.width = metrics.widthPixels;
        mLlMain.setLayoutParams(slidingPanelParameters);
        
        mLlMenu = (LinearLayout)act.findViewById(R.id.ll_menuLayout);
        leftMenuLayoutPrams = (FrameLayout.LayoutParams) mLlMenu.getLayoutParams();
        leftMenuLayoutPrams.width = viewWidth;
        mLlMenu.setLayoutParams(leftMenuLayoutPrams);
        mLlMenu.setOnTouchListener(this);
        
        mRlMy = (RelativeLayout)act.findViewById(R.id.rl_my);
        
        RelativeLayout.LayoutParams myParams = (RelativeLayout.LayoutParams) mRlMy.getLayoutParams();
        myParams.width = viewWidth - 6;
        mRlMy.setLayoutParams(myParams);
        
        mRlMy.setOnClickListener(this);
        mRlMy.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEvent.ACTION_DOWN == event.getAction()){
                    mRlMy.setBackgroundResource(R.drawable.mainmenu_1_on);
                }
                if(MotionEvent.ACTION_UP == event.getAction()){
                    mRlMy.setBackgroundResource(R.drawable.mainmenu_1);
                }
                return false;
            }
        });
        
        mRlHome = (RelativeLayout)act.findViewById(R.id.rl_home);
        
        RelativeLayout.LayoutParams homeParams = (RelativeLayout.LayoutParams) mRlHome.getLayoutParams();
        homeParams.width = viewWidth - 6;
        mRlHome.setLayoutParams(homeParams);
        
        mRlHome.setOnClickListener(this);
        mRlHome.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEvent.ACTION_DOWN == event.getAction()){
                    mRlHome.setBackgroundResource(R.drawable.mainmenu_2_on);
                }
                if(MotionEvent.ACTION_UP == event.getAction()){
                    mRlHome.setBackgroundResource(R.drawable.mainmenu_2);
                }
                return false;
            }
        });
        
        mRlCommunity = (RelativeLayout)act.findViewById(R.id.rl_community);
        
        RelativeLayout.LayoutParams commuParams = (RelativeLayout.LayoutParams) mRlCommunity.getLayoutParams();
        commuParams.width = viewWidth - 6;
        mRlCommunity.setLayoutParams(commuParams);
        
        mRlCommunity.setOnClickListener(this);
        mRlCommunity.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEvent.ACTION_DOWN == event.getAction()){
                    mRlCommunity.setBackgroundResource(R.drawable.mainmenu_3_on);
                }
                if(MotionEvent.ACTION_UP == event.getAction()){
                    mRlCommunity.setBackgroundResource(R.drawable.mainmenu_3);
                }
                return false;
            }
        });
        
        mRlShare = (RelativeLayout)act.findViewById(R.id.rl_share);
        
        RelativeLayout.LayoutParams shareParams = (RelativeLayout.LayoutParams) mRlShare.getLayoutParams();
        shareParams.width = viewWidth - 6;
        mRlShare.setLayoutParams(shareParams);
        
        mRlShare.setOnClickListener(this);
        mRlShare.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEvent.ACTION_DOWN == event.getAction()){
                    mRlShare.setBackgroundResource(R.drawable.mainmenu_4_on);
                }
                if(MotionEvent.ACTION_UP == event.getAction()){
                    mRlShare.setBackgroundResource(R.drawable.mainmenu_4);
                }
                return false;
            }
        });
        
        mRlRequest = (RelativeLayout)act.findViewById(R.id.rl_request);
        
        RelativeLayout.LayoutParams requestParams = (RelativeLayout.LayoutParams) mRlRequest.getLayoutParams();
        requestParams.width = viewWidth - 6;
        mRlRequest.setLayoutParams(requestParams);
        
        mRlRequest.setOnClickListener(this);
        mRlRequest.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEvent.ACTION_DOWN == event.getAction()){
                    mRlRequest.setBackgroundResource(R.drawable.mainmenu_5_on);
                }
                if(MotionEvent.ACTION_UP == event.getAction()){
                    mRlRequest.setBackgroundResource(R.drawable.mainmenu_5);
                }
                return false;
            }
        });
        
        mRlEvent = (RelativeLayout)act.findViewById(R.id.rl_event);
        
        RelativeLayout.LayoutParams eventParams = (RelativeLayout.LayoutParams) mRlEvent.getLayoutParams();
        eventParams.width = viewWidth - 6;
        mRlEvent.setLayoutParams(eventParams);
        
        mRlEvent.setOnClickListener(this);
        mRlEvent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEvent.ACTION_DOWN == event.getAction()){
                    mRlEvent.setBackgroundResource(R.drawable.mainmenu_6_on);
                }
                if(MotionEvent.ACTION_UP == event.getAction()){
                    mRlEvent.setBackgroundResource(R.drawable.mainmenu_6);
                }
                return false;
            }
        });
        
        mLlMenuAd = (LinearLayout)act.findViewById(R.id.ll_menu_ad);
        
        RelativeLayout.LayoutParams adParams = (RelativeLayout.LayoutParams) mLlMenuAd.getLayoutParams();
        adParams.width = viewWidth - 6;
        mLlMenuAd.setLayoutParams(adParams);
        
        
        mBtnExit = (ImageButton)act.findViewById(R.id.btn_exit);
        mBtnExit.setOnClickListener(this);
        
        mIvDimView = (ImageView)act.findViewById(R.id.iv_dim_view);
        
        RelativeLayout.LayoutParams dimparams = (RelativeLayout.LayoutParams) mIvDimView.getLayoutParams();
        dimparams.width = act.getWindowManager().getDefaultDisplay().getWidth() - viewWidth;
        
        mIvDimView.setLayoutParams(dimparams);
    }
    
    @Override
    public void onClick(View v) {
        Log.i("sykim","LeftMenu_onClick START");
        Intent intent;
        
        if (isLeftExpanded){
            switch(v.getId()){
                case R.id.rl_my:   // My프리윌
                    intent = new Intent(act, MySettingActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    act.startActivity(intent);
                    act.finish();
                    break;
                case R.id.rl_home: // 홈으로
                    String phone_num = UtilCons.MY_PHONE_NUM;
                    
                    if(phone_num.contains("+")){
                        phone_num = phone_num.replace("+82", "0");
                    }
                    
                    String allURL = UrlCons.URL_MAIN + phone_num;
                    
                    intent = new Intent(act, MainActivity.class);
                    intent.putExtra("Url", allURL);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    act.startActivity(intent);
                    act.finish();
                    break;
                case R.id.rl_community:  // 커뮤니티
                    intent = new Intent(act, MainActivity.class);
                    intent.putExtra("Url", UrlCons.URL_MENU_COMMUNITY);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    act.startActivity(intent);
                    act.finish();
                    break;
                case R.id.rl_share:   // 공유하기
                    intent = new Intent(act, MainActivity.class);
                    intent.putExtra("Url", UrlCons.URL_MENU_SHARE);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    act.startActivity(intent);
                    act.finish();
                    break;
                case R.id.rl_request:   // 요청하기
                    intent = new Intent(act, MainActivity.class);
                    intent.putExtra("Url", UrlCons.URL_MENU_REQUEST);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    act.startActivity(intent);
                    act.finish();
                    break;
                case R.id.rl_event:   // 이벤트
                    intent = new Intent(act, MainActivity.class);
                    intent.putExtra("Url", UrlCons.URL_MENU_EVENT);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    act.startActivity(intent);
                    act.finish();
                    break;
                case R.id.btn_exit:
                    showLeftMenu();
                    break;
            }
        }
        
    }
    
    /**
     * 왼쪽 메뉴를 보여주고, 없애주는 함수
     * isLeftExpanded = true 이면 보여지고 있음.
     * isLeftExpanded = false 이면 보이지 않고 있음. 
     */
    public void showLeftMenu() {
        Log.i("sykim","LeftMenu_showLeftMenu START");
        Log.e("sykim","sort :: "+sort);
        // 왼쪽 메뉴를 부른 Activity 가 MySettingActivity 일 때,
        if(sort == 1){
            mScrollMySetting = (ScrollView)act.findViewById(R.id.scroll_my_setting);
            /*mScrollMySetting.setOnTouchListener(new OnTouchListener() {
                
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    Log.d("sykim","isLeftExpanded :: "+isLeftExpanded);
                    if(isLeftExpanded){
                        return true;
                    }else
                        return false;
                }
            });*/
        }
        FrameLayout viewGroup = (FrameLayout)act.findViewById(R.id.fl_webview);
        
        // 왼쪽 메뉴가 보여지고 있지 않을 때,
        if (!isLeftExpanded) {
            
            isLeftExpanded = true;
            
            new LeftMenuOpenAnimation(mLlMain, viewWidth,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.6675f, 0, 0.0f, 0, 0.0f);
            
            //FrameLayout viewGroup = (FrameLayout)act.findViewById(R.id.fl_webview);
            enableDisableViewGroup(viewGroup, false);
            
            Log.e("sykim","1");
            mIvDimView.setVisibility(View.VISIBLE);
            
            iv.setVisibility(View.GONE);
            
//            if(sort == 1){
//                mScrollMySetting.requestDisallowInterceptTouchEvent(true);
//                mLlMenu.setFocusable(true);
//                mLlMenu.requestFocus();
//            }
            
        }
        // 왼쪽 메뉴가 보여지고 있을 때,
        else {
            isLeftExpanded = false;
                
            new LeftMenuCloseAnimation(mLlMain, viewWidth,
                    Animation.RELATIVE_TO_SELF, 0.6675f,
                    Animation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f);
                
            //FrameLayout viewGroup = (FrameLayout)act.findViewById(R.id.fl_webview);
            enableDisableViewGroup(viewGroup, true);
            
            Log.e("sykim","2");
            mIvDimView.setVisibility(View.GONE);
            
            iv.setVisibility(View.VISIBLE);
            
//            if(sort == 1){
//                mScrollMySetting.requestDisallowInterceptTouchEvent(false);
//            }
            
        }
        
    }
    
    public static void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
        Log.i("sykim","LeftMenu_enableDisableViewGroup START");
        int childCount = viewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            
            View view = viewGroup.getChildAt(i);
            view.setEnabled(enabled);
            
            if (view instanceof ViewGroup) {
                enableDisableViewGroup((ViewGroup) view, enabled);
            }
        }
        Log.d("sykim","end");
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        /**
         * 오른쪽/왼쪽 움직임을 알기 위한 변수
         */
        float distance = 0;
        
        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                pressedX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                distance = pressedX - event.getX();
                break;
        }
        
        // 드래그 거리가 100이 되지 않으면 왼쪽 메뉴가 사라지지 않는다.
        if(Math.abs(distance) < 100){
            return true;
        }
        
        // 왼쪽으로 드래그시 왼쪽 메뉴가 사라진다.
        if(distance > 0){
            showLeftMenu();
        }
        
        return true;
    }

}
